package com.xinlong.shop.framework.security.hander;

import com.xinlong.shop.framework.common.R;
import com.xinlong.shop.framework.security.constant.HttpStatusConstants;
import com.xinlong.shop.framework.util.JsonUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义认证失败处理
 * @Author Sylow
 * @Date 2022/5/27
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint
{

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        Integer code = HttpStatusConstants.UNAUTHORIZED;
        String msg ="认证失败，无法访问系统资源";

        response.getWriter().println(JsonUtil.objectToJson(R.error(code, msg)));
        response.getWriter().flush();

    }
}
